/*
 * @Autor: dingxiaolin
 * @Date: 2020-04-14 13:30:31
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-04-17 14:19:06
 */
const getRawBody = require('raw-body');
const request = require('request-promise')
const key = "fdd94fbcec6146c6ad38966099ec1f3d"
// 查询城市天气||Get||city=?
const search = (city) => {
    var options = {
        uri: 'http://apis.juhe.cn/simpleWeather/query',
        qs: {
            city: city,
            key: key
        },
        json: true // Automatically parses the JSON string in the response
    };

    const reqObj = request(options)
    return reqObj
}

// 入口函数
module.exports.handler = function (req, resp, context) {
    getRawBody(req, async (err, body) => {
        if (req.queries.city) {
            const data = await search(req.queries.city)
            if (data.reason.includes('查询成功')) {
                await sendResp(data.result)
            }
            else {
                await sendResp({
                    data: "未查询到数据"
                })
            }
        } else {
            await sendResp({
                data: "请输入查询city"
            })
        }
    });

    // 返回
    sendResp = (data) => {
        resp.setHeader('content-type', 'application/json');
        try {
            resp.send(JSON.stringify({
                success: true,
                data: data
            }));
        }
        catch (err) {
            resp.send(JSON.stringify({
                success: false,
                data: err.message
            }));
        }
    }

}